package com.zwjlg.baselibrary;

import android.content.Context;
import android.os.Environment;

import com.iceteck.silicompressorr.SiliCompressor;

import java.io.File;

/**
 * ================================================
 * <p> 视频压缩工具
 * Created by ligang on 2021/4/2 14:38
 * ================================================
 */
public class VideoCompressorUtil {
    private static VideoCompressorUtil instanse;
    private static File tempVideoDir;

    static {

    }

    private VideoCompressorUtil() {

    }

    public static VideoCompressorUtil getInstance() {
        if (instanse == null) {
            synchronized (VideoCompressorUtil.class) {
                if (instanse == null) {
                    instanse = new VideoCompressorUtil();
                }
            }
        }
        return instanse;
    }


    public void compress(Context context, String videoPath, Callback callback) {
        if (tempVideoDir == null) {
            tempVideoDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + context.getPackageName() + File.separator + "video" + File.separator + "temp");
        }
        if (!tempVideoDir.exists()) {
            tempVideoDir.mkdirs();
        }
        new Thread(new CompressTashRunnable(callback, context, videoPath)).start();

    }

    private class CompressTashRunnable implements Runnable {
        private Callback callback;
        private Context context;
        private String videoPath;

        public CompressTashRunnable(Callback callback, Context context, String videoPath) {
            this.callback = callback;
            this.context = context;
            this.videoPath = videoPath;
        }

        @Override
        public void run() {
            try {
                String resultPath = SiliCompressor.with(context).compressVideo(videoPath, tempVideoDir.getAbsolutePath(), 0, 0, 2200000);
                if (callback != null) {
                    callback.onCompressSuccess(videoPath, resultPath);
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (callback != null) {
                    callback.onCompressFailed(videoPath);
                }
            }
        }
    }

    public interface Callback {
        void onCompressSuccess(String srcPath, String resultPath);

        void onCompressFailed(String srcPath);
    }
}
